require('dotenv').config();
const jwt = require('jsonwebtoken');

// 获取 secretKey
const secretKey = process.env.JWT_SECRET_KEY;
if (!secretKey) {
    console.error('JWT_SECRET_KEY is not defined');
    process.exit(1); // 如果没有密钥，退出程序
}

const authMiddleware = (req, res, next) => {
    const authorizationHeader = req.headers['authorization'];
    console.log('Authorization header:', authorizationHeader); // 打印出 Authorization 头部

    const token = authorizationHeader?.split(' ')[1];
    console.log('Token:', token); // 打印出 token

    if (!token) {
        return res.status(403).json({ message: 'No token provided' });
    }

    jwt.verify(token, secretKey, (err, decoded) => {
        if (err) {
            console.error('Token verification failed:', err);
            return res.status(401).json({ message: 'Invalid or expired token' });
        }

        console.log('Decoded token:', decoded);  // 打印 decoded token
        req.user = decoded;
        next();
    });
};

module.exports = authMiddleware;
